#include "resetdialog.h"
#include "ui_resetdialog.h"
#include "clickedlabel.h"
#include "httpmgr.h"

ResetDialog::ResetDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::ResetDialog)
{
    ui->setupUi(this);

    //设置所有lineedit居中属性
    ui->user_edit->setAlignment(Qt::AlignCenter);
    ui->email_edit->setAlignment(Qt::AlignCenter);
    ui->pass_edit->setAlignment(Qt::AlignCenter);
    ui->verify_edit->setAlignment(Qt::AlignCenter);

    //设置浮动显示手形状
    ui->resetpass_visible->setCursor(Qt::PointingHandCursor);
    ui->resetpass_visible->SetState("unvisible", "unvisible_hover", "",
                                    "visible"  , "visible_hover"  , "");

    //设置错误属性
    repolish(ui->reset_error_tip);//刷新状态
    ui->reset_error_tip->clear();//清除掉提示信息    初始设置为空字符

    //设定文本输入框为密码模式
    ui->pass_edit->setEchoMode(QLineEdit::Password);

    //连接点击事件
    connect(ui->resetpass_visible, &ClickedLabel::clicked, this, [this]() {
        auto state = ui->resetpass_visible->GetCurState();
        if (state == ClickLabelState::Normal) {
            ui->pass_edit->setEchoMode(QLineEdit::Password);
        }
        else {
            ui->pass_edit->setEchoMode(QLineEdit::Normal);
        }
        qDebug() << "Label was clicked!";
        });

    connect(ui->user_edit,&QLineEdit::editingFinished,this,[this](){
        checkUserValid();
    });

    connect(ui->email_edit, &QLineEdit::editingFinished, this, [this](){
        checkEmailValid();
    });

    connect(ui->pass_edit, &QLineEdit::editingFinished, this, [this](){
        checkPassValid();
    });


    connect(ui->verify_edit, &QLineEdit::editingFinished, this, [this](){
        checkVerifyValid();
    });

    //连接reset相关信号和注册处理回调
    initHttpHandlers();

    //初始化http服务
    connect(HttpMgr::GetInstance().get(), &HttpMgr::sig_reset_mod_finish, this,
            &ResetDialog::slot_reset_mod_finish);

}

ResetDialog::~ResetDialog()
{
    qDebug() << "ResetDialog was destructed";
    delete ui;
}


void ResetDialog::showTip(QString str, bool b_ok)
{
    //正常状态置1，错误状态置0
    //设定标签的初始颜色
    if(b_ok){
        ui->reset_error_tip->setProperty("state","normal");
    }else{
        ui->reset_error_tip->setProperty("state","error");
    }

    ui->reset_error_tip->setText(str);

    repolish(ui->reset_error_tip);//刷新状态
}

bool ResetDialog::checkUserValid()
{
    if(ui->user_edit->text() == ""){
        AddTipErr(TipErr::TIP_USER_ERR, tr("用户名不能为空"));
        return false;
    }

    DelTipErr(TipErr::TIP_USER_ERR);
    return true;
}

bool ResetDialog::checkPassValid()
{
    auto pass = ui->pass_edit->text();

    if(pass.length() < 6 || pass.length()>15){
        //提示长度不准确
        AddTipErr(TipErr::TIP_PWD_ERR, tr("密码长度应为6~15"));
        return false;
    }

    // 创建一个正则表达式对象，按照上述密码要求
    // 这个正则表达式解释：
    // ^[a-zA-Z0-9!@#$%^&*]{6,15}$ 密码长度至少6，可以是字母、数字和特定的特殊字符
    QRegularExpression regExp("^[a-zA-Z0-9!@#$%^&*.]{6,15}$");
    bool match = regExp.match(pass).hasMatch();
    if(!match){
        //提示字符非法
        AddTipErr(TipErr::TIP_PWD_ERR, tr("不能包含非法字符"));
        return false;;
    }

    DelTipErr(TipErr::TIP_PWD_ERR);

    return true;
}

bool ResetDialog::checkEmailValid()
{
    //验证邮箱的地址正则表达式
    auto email = ui->email_edit->text();
    // 邮箱地址的正则表达式
    QRegularExpression regex(R"((\w+)(\.|_)?(\w*)@(\w+)(\.(\w+))+)");
    bool match = regex.match(email).hasMatch(); // 执行正则表达式匹配
    if(!match){
        //提示邮箱不正确
        AddTipErr(TipErr::TIP_EMAIL_ERR, tr("邮箱地址不正确"));
        return false;
    }

    DelTipErr(TipErr::TIP_EMAIL_ERR);
    return true;
}

bool ResetDialog::checkVerifyValid()
{
    auto pass = ui->verify_edit->text();
    if(pass.isEmpty()){
        AddTipErr(TipErr::TIP_VERIFY_ERR, tr("验证码不能为空"));
        return false;
    }

    DelTipErr(TipErr::TIP_VERIFY_ERR);
    return true;
}

void ResetDialog::AddTipErr(TipErr te, QString tips)
{
    _tip_errs[te] = tips;
    showTip(tips, false);
}

void ResetDialog::DelTipErr(TipErr te)
{
    _tip_errs.remove(te);
    if(_tip_errs.empty()){
        ui->reset_error_tip->clear();
        return;
    }

    showTip(_tip_errs.first(), false);
}

//处理回包逻辑
void ResetDialog::initHttpHandlers()
{
    //注册获取验证码回包逻辑
    _handlers.insert(ReqId::ID_GET_VERIFY_CODE, [this](QJsonObject jsonObj){
        int error = jsonObj["error"].toInt();
        if(error != ErrorCodes::SUCCESS){
            showTip(tr("参数错误"),false);
            return;
        }
        auto email = jsonObj["email"].toString();
        showTip(tr("验证码已发送到邮箱，注意查收"), true);
        qDebug()<< "email is " << email ;
    });

    //注册重置密码回包逻辑
    _handlers.insert(ReqId::ID_RESET_PWD, [this](QJsonObject jsonObj){
        int error = jsonObj["error"].toInt();
        if(error != ErrorCodes::SUCCESS){
            showTip(tr("参数错误"),false);
            qDebug() << "错误码" << error;
            return;
        }
        auto email = jsonObj["email"].toString();
        showTip(tr("重置成功,点击返回登录"), true);
        qDebug()<< "email is " << email ;
        qDebug()<< "user uid is " <<  jsonObj["uid"].toString();
    });
}

void ResetDialog::slot_reset_mod_finish(ReqId id, QString res, ErrorCodes err)
{
    //不成功
    if(err != ErrorCodes::SUCCESS)
    {
        showTip(tr("网络请求错误"), false);
        return;
    }

    //解析JSON字符串,将 res 转换为 QByteArray
    QJsonDocument jsonDoc = QJsonDocument::fromJson(res.toUtf8()); //xxx.json文件了
    //Json解析失败
    if(jsonDoc.isNull())//文件为空，解析失败
    {
        showTip(tr("Json解析失败"),false);
        return;
    }

    //Json解析错误
    if(!jsonDoc.isObject())
    {
        showTip(tr("Json解析失败"),false); //提示是给到用户的，错误类型写入到日志文件中
        return;
    }

    //丢给处理器具体的函数处理相应内容
    _handlers[id](jsonDoc.object());
    return;
}

//返回登陆页
void ResetDialog::on_return_btn_clicked()
{
    emit sigSwitchLogin();
}

//获取验证码服务
void ResetDialog::on_verify_btn_clicked()
{
    auto email = ui->email_edit->text();
    QRegularExpression regex(R"((\w+)(\.|_)?(\w*)@(\w+)(\.(\w+))+)"); //正则表达式
    bool match = regex.match(email).hasMatch();
    if(match){
        //发送http验证码
        QJsonObject json_obj;
        json_obj["email"] = email;
        HttpMgr::GetInstance()->PostHttpReq(gate_url_prefix + "/get_verifycode" /*测试用QUrl("http://localhost:8080/get_verifycode")*/,
                                            json_obj,ReqId::ID_GET_VERIFY_CODE,Modules::RESETMOD);

    }else{
        showTip(tr("邮箱地址不正确"),false);
    }
}

//确认重置密码
void ResetDialog::on_confirm_btn_clicked()
{
    bool valid = checkUserValid();
    if(!valid){
        return;
    }
    valid = checkEmailValid();
    if(!valid){
        return;
    }
    valid = checkPassValid();
    if(!valid){
        return;
    }
    valid = checkVerifyValid();
    if(!valid){
        return;
    }

    //发送http重置用户请求
    QJsonObject json_obj;
    json_obj["user"] = ui->user_edit->text();
    json_obj["email"] = ui->email_edit->text();
    json_obj["passwd"] = md5Encrypt(ui->pass_edit->text());
    json_obj["verifycode"] = ui->verify_edit->text();
    HttpMgr::GetInstance()->PostHttpReq(QUrl(gate_url_prefix+"/reset_password"),
                                        json_obj, ReqId::ID_RESET_PWD,Modules::RESETMOD);
}

